package br.com.peperoncino.controller.cardapio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Pagination;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import br.com.peperoncino.entity.ItemCardapio;
import br.com.peperoncino.entity.TipoItem;
import br.com.peperoncino.model.ItemCardapioDAO;
import br.com.peperoncino.utils.StringHelper;

public class ItemCardapioController implements Initializable{

	@FXML
	TableView<ItemCardapioTable> tabelaCardapio;
	
	@FXML
	TableColumn<ItemCardapioTable, Integer> iID;
	
	@FXML
	TableColumn<ItemCardapioTable, String> iNome;

	@FXML
	TableColumn<ItemCardapioTable, String> iDescricao;
	
	@FXML
	TableColumn<ItemCardapioTable, Float> iValor;
	
	@FXML
	TableColumn<ItemCardapioTable, String> iTipoItem;
	
	//DEFINE FORM
	@FXML
	TextField nomeInput;
	
	@FXML
	TextField valorInput;
	
	@FXML
	ComboBox<TipoItem> tipoItemInput = new ComboBox<TipoItem>();
	
	@FXML
	Button apagar;
	
	@FXML
	Button limpar;
	
	@FXML
	Button pesquisar;

	@FXML
	Button novo;
	
	@FXML
	Label nameLabel;
	
	@FXML
	Label dateLabel;
	
	@FXML
	Label priceLabel;
	
	@FXML
	Pagination paginacao = new Pagination();
	
	/*PAGINACAO*/
	private final Integer QTD_REGISTROS_PAGINACAO = 4;
	private ItemCardapio dadosFiltro;
	
	
	//index for delete item
	private IntegerProperty index = new SimpleIntegerProperty(-1);
	private Integer indexClicada = null;
	
	final ObservableList<ItemCardapioTable> dadosCardapioTabela = FXCollections.observableArrayList();
	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		
		ItemCardapioDAO itemCardapioDAO = new ItemCardapioDAO();
		Integer quantidade = itemCardapioDAO.recuperaTotal(null);
		
		trataPaginacao(quantidade) ;
		trataTabela(itemCardapioDAO);
		trataCombo();
		
		paginacao.currentPageIndexProperty().addListener(new ChangeListener<Number>(){
			@Override
			public void changed(ObservableValue<? extends Number> arg0,	Number oldNumber, Number number) {
				List<ItemCardapio> cardapios = new ItemCardapioDAO().pesquisar(dadosFiltro, number.intValue() * QTD_REGISTROS_PAGINACAO, QTD_REGISTROS_PAGINACAO);
				tabelaCardapio.setItems(ItemCardapioTable.toCardapioTabela(cardapios));
			}
		});
	}
	
	private void trataCombo() {
		
		/*popula o combo*/
		tipoItemInput.setItems(FXCollections.observableArrayList(Arrays.asList(TipoItem.values())));
		tipoItemInput.getItems().add(0, null);
	}

	private void trataTabela(ItemCardapioDAO itemCardapioDAO) {
		
		List<ItemCardapio> cardapios = itemCardapioDAO.pesquisar(null, 0, QTD_REGISTROS_PAGINACAO);
		
		tabelaCardapio.setItems(ItemCardapioTable.toCardapioTabela(cardapios));
		
		iID.setCellValueFactory(new PropertyValueFactory<ItemCardapioTable,Integer>("rID"));
		iNome.setCellValueFactory(new PropertyValueFactory<ItemCardapioTable,String>("rNome"));
		iDescricao.setCellValueFactory(new PropertyValueFactory<ItemCardapioTable,String>("rDescricao"));
		iValor.setCellValueFactory(new PropertyValueFactory<ItemCardapioTable,Float>("rValor"));
		iTipoItem.setCellValueFactory(new PropertyValueFactory<ItemCardapioTable,String>("rTipoItem"));
		
		//captura o indice quando clicado na linha da tabela
		tabelaCardapio.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Object>() {
			
			@Override
			public void changed(ObservableValue<?> observable, Object oldValue, Object newValue){
				index.set(tabelaCardapio.getItems().indexOf(newValue));
				System.out.println("OK index is:" + tabelaCardapio.getItems().indexOf(newValue));
			}
		});
		
	}

	@FXML
	public void aoLimpar(ActionEvent event){
		limparForm();
	}

	@FXML
	public void aoPesquisar(ActionEvent event){
		
		BigDecimal valor = !StringHelper.ehBrancoOuNulo(valorInput.getText()) ? new BigDecimal(valorInput.getText()) : null;
		
		this.dadosFiltro = new ItemCardapio(null, nomeInput.getText(), null, valor, tipoItemInput.getValue());
		
		ItemCardapioDAO itemCardapioDAO = new ItemCardapioDAO();
		Integer quantidade = itemCardapioDAO.recuperaTotal(dadosFiltro);
		
		List<ItemCardapio> cardapios = new ItemCardapioDAO().pesquisar(dadosFiltro, 0, QTD_REGISTROS_PAGINACAO);
		tabelaCardapio.setItems(ItemCardapioTable.toCardapioTabela(cardapios));
		
		paginacao.setCurrentPageIndex(0);
		trataPaginacao(quantidade);
	}
	
	private void trataPaginacao(Integer quantidade) {
		
		Integer tratamentoQuantidade = quantidade <= QTD_REGISTROS_PAGINACAO ? 1 : (quantidade/QTD_REGISTROS_PAGINACAO) + 1;
		
		paginacao.setPageCount(tratamentoQuantidade); 
		paginacao.setMaxPageIndicatorCount(tratamentoQuantidade  < 10 ? tratamentoQuantidade : 10);
	}

	@FXML
	public void aoEditar(MouseEvent event){
		
		if(indexClicada == null){
			indexClicada = index.get();
		}else if(indexClicada == index.get()){
			
			try {
				ItemCardapioTable itemCardapioTable = tabelaCardapio.getItems().get(index.get());
				FXMLLoader fxmlLoader = new FXMLLoader();
				AnchorPane page = (AnchorPane) fxmlLoader.load(getClass().getResource("ManterItemCardapio.fxml").openStream());
				((ManterItemCardapioController)fxmlLoader.getController()).carregaValoresItemCardapio(itemCardapioTable.toItemCardapio());
				Stage stage = new Stage();
				Scene scene = new Scene(page);
				Image img;
				img = new Image(new FileInputStream(System.getProperty("user.dir")+ "\\img\\saopaulo.png"));
				stage.setScene(scene);
				stage.setTitle("Manter Item Cardapio");
				stage.getIcons().add(img);  
				stage.show();
			} catch (FileNotFoundException e) {
				System.out.println(e.getMessage());
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
			
		}else if(indexClicada != index.get()){
			indexClicada = index.get();
		}
		
	}

	@FXML
	public void aoIncluirItemCardapio(ActionEvent event){
		
		try {
			Stage stage = new Stage();
			AnchorPane page = (AnchorPane) FXMLLoader.load(getClass().getResource("ManterItemCardapio.fxml"));
			Scene scene = new Scene(page);
			Image img;
			img = new Image(new FileInputStream(System.getProperty("user.dir")+ "\\img\\saopaulo.png"));
			stage.setScene(scene);
			stage.setTitle("Manter Item Cardapio");
			stage.getIcons().add(img);  
			stage.show();
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
			
//		Cardapio dadosFiltro = new Cardapio(null, nomeInput.getText(), null, null, tipoItemInput.getValue());
//		List<Cardapio> cardapios = new CardapioDAO().pesquisar(dadosFiltro);
//		tabelaCardapio.setItems(CardapioTable.toCardapioTabela(cardapios));
		
	}

	private void limparForm(){
		
		nomeInput.setText("");
		valorInput.setText("");
		
		tipoItemInput.setValue(null);
		
		tabelaCardapio.setItems(ItemCardapioTable.toCardapioTabela(new ArrayList<ItemCardapio>()));
		
		nomeInput.getStyleClass().remove("error");
		valorInput.getStyleClass().remove("error");
		
		paginacao.setMaxPageIndicatorCount(1);
		paginacao.setPageCount(1); 
	}
	
	
}
